// composables/useMixins.js
import { ref, reactive } from 'vue'
import Request from '@/commons/request'
import Message from '@/components/message'
import storage from '@/commons/storage'

/**
 * 通用 mixins composable
 * @param {Object} urlConfig - URL 配置对象
 * @returns {Object} 包含所有状态和方法的对象
 */
export function useMixins(urlConfig = {}) {
  // 响应式数据
  const queryParam = reactive({})
  const desserts = ref([])
  const loading = ref(false)
  const superQueryParams = ref('')
  const page = reactive({
    pageno: 1,
    limit: 10
  })
  const pageData = ref({})
  const sumup = ref({})
  const pageDataCopy = ref([])
  const overlay = ref(false)
  const user = ref({})

  // URL 配置
  const url = reactive(urlConfig)

  /**
   * 获取查询参数
   * @returns {Object} 查询参数对象
   */
  const getQueryParams = () => {
    user.value = storage.get('user')
    if (!queryParam.areaCode) {
      queryParam.areaCode = user.value?.areacode
    }
    const codex = Object.assign({}, queryParam)
    const params = {
      pageno: page.pageno,
      limit: page.limit,
      codex: codex
    }
    return params
  }

  /**
   * 加载页面数据
   */
  const loadPage = () => {
    if (!url.list) {
      Message.toast('请先设置url.list属性', { color: 'warning' })
      return
    }
    const params = getQueryParams()
    loading.value = true

    // 兼容处理 vtk 对象
    if (window.$vtk?.message?.loading) {
      window.$vtk.message.loading.show()
    }

    Request.postJson(url.list, params)
      .then((res) => {
        if (window.$vtk?.message?.loading) {
          window.$vtk.message.loading.hide()
        }

        if (res.meta.success || res.data) {
          desserts.value = res.data?.rows || []
          pageData.value = res.data
          sumup.value = res.data.sumup ? res.data.sumup : {}
          pageDataCopy.value = res.data
        }
        loading.value = false
      })
      .catch((error) => {
        console.error('加载页面数据失败:', error)
        loading.value = false
        if (window.$vtk?.message?.loading) {
          window.$vtk.message.loading.hide()
        }
      })
  }

  /**
   * 搜索查询
   */
  const searchQuery = () => {
    page.pageno = 1
    page.limit ??= 10
    loadPage()
  }

  /**
   * 分页变化处理
   * @param {Object} pageInfo - 分页信息
   */
  const getListPage = (pageInfo) => {
    page.pageno = pageInfo.pageno
    page.limit = pageInfo.limit
    loadPage()
  }

  /**
   * 删除项
   * @param {string|number} id - 要删除的项ID
   * @param {string} text - 确认提示文本
   */
  const deleteItem = (id, text) => {
    if (!url.delete) {
      Message.toast('请设置url.delete属性!', { color: 'warning' })
      return
    }

    Message.confirm(
      { title: '确认删除', text: text ? text : '是否删除?' },
      (result) => {
        if (result) {
          Request.getForm(url.delete, { id: id })
            .then((res) => {
              if (res.meta.success) {
                Message.toast('删除成功', { color: 'success' })
                loadPage()
              } else {
                Message.toast('删除失败', { color: 'warning' })
              }
            })
            .catch((error) => {
              console.error('删除失败:', error)
              Message.toast('删除失败', { color: 'warning' })
            })
        }
      }
    )
  }

  /**
   * 复制项
   * @param {string|number} id - 要复制的项ID
   * @param {string} text - 确认提示文本
   */
  const copyItem = (id, text) => {
    if (!url.copy) {
      Message.toast('请设置url.copy!', { color: 'warning' })
      return
    }

    Message.confirm(
      { title: '拷贝', text: text ? text : '是否确认拷贝当前数据?' },
      (result) => {
        if (result) {
          Request.getForm(url.copy, { id: id })
            .then((res) => {
              if (res.meta.success) {
                Message.toast('拷贝成功', { color: 'success' })
                loadPage()
              } else {
                Message.toast('拷贝失败', { color: 'warning' })
              }
            })
            .catch((error) => {
              console.error('拷贝失败:', error)
              Message.toast('拷贝失败', { color: 'warning' })
            })
        }
      }
    )
  }

  /**
   * 编辑项
   * @param {Object} record - 要编辑的记录
   * @param {Object} modalFormRef - 模态框引用
   */
  const edit = (record, modalFormRef) => {
    if (modalFormRef?.value) {
      modalFormRef.value.edit(record)
    }
  }

  /**
   * 添加新项
   * @param {Object} modalFormRef - 模态框引用
   */
  const add = (modalFormRef) => {
    if (modalFormRef?.value) {
      modalFormRef.value.add()
    }
  }

  /**
   * 模态框确认回调
   */
  const modalFormOk = () => {
    loadPage()
  }

  /**
   * 导出数据
   */
  const expData = () => {
    overlay.value = true

    if (window.$vtk?.message?.loading) {
      window.$vtk.message.loading.show()
    }

    const params = getQueryParams()
    Request.exp(url.exp, params)
      .then((res) => {
        if (window.$vtk?.message?.loading) {
          window.$vtk.message.loading.hide()
        }

        if (res) {
          const disposition = res.headers['content-disposition']
          const filename = decodeURI(
            disposition.substring(
              disposition.indexOf('filename=') + 9,
              disposition.length
            )
          )
          const blob = new Blob([res.data], {
            type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })

          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob)
          } else {
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.download = filename
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        }
        overlay.value = false
      })
      .catch((error) => {
        console.error('导出数据失败:', error)
        overlay.value = false
        if (window.$vtk?.message?.loading) {
          window.$vtk.message.loading.hide()
        }
      })
  }

  /**
   * 重置查询参数
   */
  const resetQueryParams = () => {
    Object.keys(queryParam).forEach(key => {
      delete queryParam[key]
    })
  }

  /**
   * 重置分页
   */
  const resetPage = () => {
    page.pageno = 1
    page.limit = 10
  }

  /**
   * 更新 URL 配置
   * @param {Object} newUrlConfig - 新的 URL 配置
   */
  const updateUrlConfig = (newUrlConfig) => {
    Object.assign(url, newUrlConfig)
  }

  // 返回所有状态和方法
  return {
    // 响应式数据
    queryParam,
    desserts,
    loading,
    superQueryParams,
    page,
    pageData,
    sumup,
    pageDataCopy,
    overlay,
    user,
    url,

    // 方法
    getQueryParams,
    loadPage,
    searchQuery,
    getListPage,
    deleteItem,
    copyItem,
    edit,
    add,
    modalFormOk,
    expData,
    resetQueryParams,
    resetPage,
    updateUrlConfig
  }
}

// 默认导出保持向后兼容
export default useMixins